﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StringToImage
{
    public class ToImage
    {
        /// <summary>
        /// 字符串生成图片
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="color">背景颜色</param>
        /// <param name="path">保存路径</param>
        public void GetImg(char str, Color color, string path)
        {
            // 创建画布
            Bitmap bmp = new Bitmap(248, 248, PixelFormat.Format24bppRgb);
            bmp.SetResolution(248, 248);
            using (Graphics g = Graphics.FromImage(bmp))
            {
                // 用白色清空 
                g.Clear(color);

                // 指定高质量的双三次插值法。执行预筛选以确保高质量的收缩。此模式可产生质量最高的转换图像。 
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;

                g.CompositingQuality = CompositingQuality.HighQuality;

                // 指定高质量、低速度呈现。 
                g.SmoothingMode = SmoothingMode.HighQuality;

                g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;

                Font f = new Font("Roboto Medium", 50, FontStyle.Bold);

                Brush b = new SolidBrush(Color.FromArgb(130, 255, 255, 255));

                StringFormat sf = new StringFormat();
                sf.LineAlignment = StringAlignment.Center;
                sf.Alignment = StringAlignment.Center; //居中

                g.DrawString(str.ToString(), f, b, new Rectangle(0, 3, 248, 248), sf);

                //将图片以指定的格式保存到到指定的位置
                bmp.Save(path + str + ".png", ImageFormat.Png);
            }

        }
    }
}
